#coding=utf-8
import datetime
from sqlalchemy.orm.exc import NoResultFound

from config import DEBUG
import sdsource.web.sina as source
from domains import *
from recorder import UpdateRecorder
from utility import str2date

def stock2db(code):
    s0 = source.get_stock(code)
    
    ipo = str2date(s0.ipo)
    s = Stock(code=s0.code, name=s0.name, ipo=ipo,
               ipo_price=s0.iprice, market=s0.market )
    
    session.commit()

def tss2db(code):
    ''' tradableshares to db.'''
    s = find_stock(code)
    
    ur = UpdateRecorder(code)
    td = datetime.date.today()
    if ur.update_ts_on and ur.update_ts_on == td:
        if DEBUG:print '今天已经更新过股票(%s)的可流通股份数量.'%s 
        return
    
    ts0 = source.get_ts(code)
    for ts in ts0.tss:
        dt = str2date(ts[0])
        n = int(ts[1])
        try:    
            TradableShare.query().filter_by(stock=s, beginning=dt, quantity=n).one()
        except NoResultFound:
            TradableShare(stock=s, beginning=dt, quantity=n)
            session.commit()
    ur.update_ts_on = td

    
